package org.ams.role.service.impl;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import org.ams.common.util.Common;
import org.ams.role.dao.RoleDao;
import org.ams.role.entity.Role;
import org.ams.role.entity.RoleAccount;
import org.ams.role.entity.RoleMenu;
import org.ams.role.service.RoleService;
import org.springframework.stereotype.Service;

@Service("roleService")
public class RoleServiceImpl implements RoleService {

	@Resource
	private RoleDao roleDao;
	
	@Override
	public List<Role> queryRoleListByMap(Map<String, Object> params) {
		return roleDao.queryRoleList(params);
	}
	
	@Override
	public List<RoleAccount> queryRoleAccountListByAccountId(Integer accountId) {
		Map<String, Object> params = new HashMap<String, Object>();
		params.put("accountId", accountId);
		return roleDao.queryRoleAccountListByMap(params);
	}

	@Override
	public List<Role> queryRoleListByPage(Map<String, Object> params) {
		return roleDao.queryRoleList(params);
	}

	@Override
	public Integer deleteRolesByIds(Map<String, Object> params) {
		Integer returnRows = roleDao.deleteRolesByIds(params);
		if(0 < returnRows){
			roleDao.deleteRoleAccountByRoleIds(params);
		}
		return returnRows;
	}

	@Override
	public Role queryRoleByMap(Map<String, Object> params) {
		List<Role> roleList = roleDao.queryRoleList(params);
		if(null != roleList && !roleList.isEmpty()){
			return roleList.get(0);
		} else {
			return new Role();
		}
	}

	@Override
	public List<RoleMenu> queryRoleMenuListByRoleId(Integer roleId) {
		Map<String, Object> params = new HashMap<String, Object>();
		params.put("roleId", roleId);
		return roleDao.queryRoleMenuListByMap(params);
	}

	@Override
	public Integer updateRole(Role role) {
		Integer returnRows = roleDao.updateRole(role);
		saveRoleMenu(role);
		return returnRows;
	}

	@Override
	public Integer saveRole(Role role) {
		Integer returnRows = roleDao.saveRole(role);
		saveRoleMenu(role);
		return returnRows;
	}
	
	private void saveRoleMenu(Role role) {
		Map<String, Object> params = new HashMap<String, Object>();
		Integer roleId = role.getRoleId();
		Integer[] menus = role.getMenus();
		if(null != menus) {
			List<Integer> idList = Common.createIdList(roleId + ",", ",");
			params.put("idList", idList);
			roleDao.deleteRoleMenuByRoleIds(params);
			for (Integer menuId : menus) {
				params.clear();
				params.put("menuId", menuId);
				params.put("roleId", roleId);
				List<RoleMenu> roleMenuList = roleDao.queryRoleMenuListByMap(params);
				if(null == roleMenuList || roleMenuList.isEmpty()){
					RoleMenu rm = new RoleMenu();
					rm.setMenuId(menuId);
					rm.setRoleId(roleId);
					rm.setCreateTime(new Date());
					roleDao.saveRoleMenu(rm);
				}
			}
		}
	}

}
